<template>
  <div class="write">
    <div class="write-header">
      <div>
        <label for="title">
          标题:
          <input id="title" type="text" v-model="title" placeholder="请输入标题" />
        </label>
        <label for="way">
          方向:
          <input id="way" type="text" v-model="way" placeholder="请输入方向" />
        </label>
      </div>
      <button @click="save(markdownTest, render)">保存</button>
    </div>
    <mavon-editor
      v-model="editContent"
      ref="md"
      :codeStyle="codeStyle"
      @save="save"
      @change="change"
      :ishljs="true"
      class="mavonWrite"
    />
  </div>
</template>

<script>
import { env } from "../http";
export default {
  data() {
    return {
      editContent: "",
      codeStyle: "vs2015",
      title: "",
      way: "",
      render: "",
      markdownTest: "",
    };
  },
  methods: {
    change(value, render) {
      this.markdownTest = value;
      this.render = render;
    },
    getAbstract(html) {
      const div = document.createElement("div");
      div.innerHTML = html;
      return div.innerText.substring(0, 30) + "...";
    },
    save(value, render) {
      if (!this.title || !this.way) {
        alert("请输入标题或方向");
        return;
      }
      const { status } = localStorage.getItem("allData");
      const body = {
        status,
        title: this.title,
        way: this.way,
        editContent: value,
        content: render,
        abstract: this.getAbstract(render),
      };
      fetch(env + "/blog/add", {
        method: "post",
        body: JSON.stringify(body),
        headers: {
          Authorization: localStorage.getItem("LoginToken"),
          "Content-Type": "application/json",
        },
      })
        .then((res) => res.json())
        .then((res) => {
          res.error === -1 &&
            this.$message.success({
              message: "新增成功",
              center: true,
            });
        });
    },
  },
};
</script>

<style scoped lang="less">
.write {
  text-align: left;
  .mavonWrite {
    height: calc(100vh - 180px);
  }
  &-header {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    input {
      border: 1px solid #d9d9d9;
      border-radius: 2px;
      margin-right: 16px;
      padding: 6px 12px;
      outline: none;
      margin-left: 4px;
    }
    button {
      border: none;
      background-color: #448ef7;
      color: #fff;
      border-radius: 3px;
      width: 80px;
      &:hover {
        opacity: 0.8;
        cursor: pointer;
      }
    }
  }
}
</style>
